package com.srwl.mytx.widget;


import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.MyFileRecordAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.MyFile;
import com.srwl.mytx.fragment.BaseFragment;
import com.srwl.mytx.service.TopicService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class MyFileRepositoryDialog extends BaseFragment implements MyFileRecordAdapter.InteractionListener {
    private static final String TAG = "MyFileRepositoryDialog";
    public static final String SELECT_PICTURE_LIMITE = "picture_limit";
    public static final String SELECT_VIDEO_LIMITE = "video_limit";
    public static final String SELECT_ONLY_ONE_TYPE = "select_only_one";
    public static final String HISTORY_SELECT = "history_select";

    @BindView(R.id.refresh_layout)
    MaterialSmoothRefreshLayout refreshLayout;
    @BindView(R.id.rv_my_file)
    RecyclerView rv_myFile;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.tv_confirm)
    TextView tv_confirm;
    @BindView(R.id.iv_back)
    ImageView iv_back;

    @BindView(R.id.tv_video_count)
    TextView tv_videoCount;
    @BindView(R.id.tv_picture_count)
    TextView tv_pictureCount;

    private MyFileRecordAdapter fileRecordAdapter;
    private List<MyFile> myFileList = new ArrayList<>();
    private List<MyFile> historySelectFiles = new ArrayList<>();
    private int page = 1;
    private boolean hasNextPage;
    private InteractionListener listener;
    private List<MyFile> selectFiles = new ArrayList<>();//当前选中的所有文件
    private ArrayList<MyFile> selectPictureFiles = new ArrayList<>();//当前选中的图片
    private ArrayList<MyFile> selectVideoFiles = new ArrayList<>();//当前选中的视频
    private int pictureLimit = 9;
    private int videoLimit = 1;
    private boolean selectOnlyOneType;//标记图片和视频是否只能选一种，默认图片和视频都可以选择

    public static MyFileRepositoryDialog newInstance(int videoLimit, int pictureLimit, boolean selectOnlyOneType, ArrayList<MyFile> historySelectFiles) {
        MyFileRepositoryDialog myFileRepositoryDialog = new MyFileRepositoryDialog();
        Bundle bundle = new Bundle();
        bundle.putInt(SELECT_VIDEO_LIMITE, videoLimit);
        bundle.putInt(SELECT_PICTURE_LIMITE, pictureLimit);
        bundle.putBoolean(SELECT_ONLY_ONE_TYPE, selectOnlyOneType);
        bundle.putParcelableArrayList(HISTORY_SELECT, historySelectFiles);
        myFileRepositoryDialog.setArguments(bundle);
        return myFileRepositoryDialog;
    }

    public static MyFileRepositoryDialog newInstance(int videoLimit, int pictureLimit, ArrayList<MyFile> historySelectFiles) {

        MyFileRepositoryDialog myFileRepositoryDialog = new MyFileRepositoryDialog();
        Bundle bundle = new Bundle();
        bundle.putInt(SELECT_VIDEO_LIMITE, videoLimit);
        bundle.putInt(SELECT_PICTURE_LIMITE, pictureLimit);
        bundle.putParcelableArrayList(HISTORY_SELECT, historySelectFiles);
        myFileRepositoryDialog.setArguments(bundle);
        return myFileRepositoryDialog;
    }

    public static MyFileRepositoryDialog newInstance(int videoLimit, int pictureLimit) {

        MyFileRepositoryDialog myFileRepositoryDialog = new MyFileRepositoryDialog();
        Bundle bundle = new Bundle();
        bundle.putInt(SELECT_VIDEO_LIMITE, videoLimit);
        bundle.putInt(SELECT_PICTURE_LIMITE, pictureLimit);
        myFileRepositoryDialog.setArguments(bundle);
        return myFileRepositoryDialog;
    }

    public static MyFileRepositoryDialog newInstance() {
        return new MyFileRepositoryDialog();
    }

//    @Override
//    public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        // setStyle(DialogFragment.STYLE_NO_TITLE, R.style.my_file_dialog_style);
//        if (getArguments() != null) {
//            pictureLimit = getArguments().getInt(SELECT_PICTURE_LIMITE, 9);
//            videoLimit = getArguments().getInt(SELECT_VIDEO_LIMITE, 1);
//            selectOnlyOneType = getArguments().getBoolean(SELECT_ONLY_ONE_TYPE, false);
//            if (getArguments().containsKey(HISTORY_SELECT)) {
//                historySelectFiles = getArguments().getParcelableArrayList(HISTORY_SELECT);
//                myFileList.addAll(historySelectFiles);
//                selectFiles.addAll(historySelectFiles);
//                setSelectRecord();
//            }
//        }
//    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getArguments() != null) {
            pictureLimit = getArguments().getInt(SELECT_PICTURE_LIMITE, 9);
            videoLimit = getArguments().getInt(SELECT_VIDEO_LIMITE, 1);
            selectOnlyOneType = getArguments().getBoolean(SELECT_ONLY_ONE_TYPE, false);
            if (getArguments().containsKey(HISTORY_SELECT)) {
                historySelectFiles = getArguments().getParcelableArrayList(HISTORY_SELECT);
                myFileList.addAll(historySelectFiles);
                selectFiles.addAll(historySelectFiles);
                setSelectRecord();
            }
        }

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView: 执行了，，，");
        View view = inflater.inflate(R.layout.layout_my_file_repository_dialog, container, false);
        ButterKnife.bind(this, view);
        iv_back.setOnClickListener(v -> getActivity().finish());
        //setButtonEnable();

        setVideoCount(0, videoLimit);
        setPictureCount(0, pictureLimit);
        loadData(true);
        initRecyclerView();
        initRefreshLayout();
        setPictureCount(selectPictureFiles.size(), pictureLimit);
        setVideoCount(selectVideoFiles.size(), videoLimit);
        checkEnableSelectVideo();
        checkEnableSelectPicture();
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onConfirm(selectVideoFiles, selectPictureFiles);
                }
            }
        });
        return view;
    }

    private void initRecyclerView() {
        fileRecordAdapter = new MyFileRecordAdapter(getActivity(), myFileList, this);
        if (videoLimit == 0) {
            fileRecordAdapter.setEnableSelectVideo(false);
        }
        if (pictureLimit == 0) {
            fileRecordAdapter.setEnableSelectPicture(false);
        }
        //行数
        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), cols);
        int finalCols = cols;
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int i) {
                if (myFileList.size() == 0) {//显示没有数据的时候，占整行
                    return finalCols;
                }
                return 1;
            }
        });
        rv_myFile.setLayoutManager(gridLayoutManager);
        rv_myFile.setAdapter(fileRecordAdapter);
    }




    private void initRefreshLayout() {
        //   refreshLayout.setEnableOldTouchHandling(true);
        refreshLayout.setDisableRefresh(true);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setEnableOverScroll(true);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {

            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage) {
                    loadData(false);
                } else {
                    refreshLayout.refreshComplete();
                }
            }
        });
    }

    private void loadData(boolean isFirst) {
        if (!Helper.getInstance().isNetworkConnected()){
            if (!isFirst) refreshLayout.refreshComplete();  //在没网络的情况下使用refresh也需要将其设置为刷新完毕，否则当网络恢复时，当前页面未被销毁的的话，则不能继续加载
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        int SIZE = 36;
        Map<String, Object> body = new HashMap<>();
        body.put("page", page);
        body.put("size", SIZE);
        if (isFirst) {
            progressBar.setVisibility(View.VISIBLE);
        }

        RetrofitManager.getInstance().createRequest(TopicService.class)
                .queryMyFile(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.INVISIBLE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            return;
                        }
                        JSONObject pageInfo = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse: 获取历史发布文件记录完成" + pageInfo.toJSONString());
                        hasNextPage = pageInfo.getBoolean("hasNextPage");


                        List<MyFile> myFiles = pageInfo.getJSONArray("list").toJavaList(MyFile.class);
                        removeHistorySelect(myFiles);
                        myFileList.addAll(myFiles);
                        int size = myFiles.size();
                        Log.d(TAG, "onResponse:  historySelectFiles.size()  " + historySelectFiles.size());


                        //setButtonEnable();
                        if (isFirst) {
                            fileRecordAdapter.notifyDataSetChanged();
                        } else {
                            fileRecordAdapter.notifyItemRangeInserted(myFileList.size() - size, size);
                        }
                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> {
                                if (getActivity() != null) {
                                    refreshLayout.setFooterView(new NodataFooter(getActivity()));
                                }
                            }, 1000);
                        }

                        page++;
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                        if (isFirst) {
                            progressBar.setVisibility(View.INVISIBLE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });

    }

    /**
     * 设置上一次的选择记录
     */
    private void setSelectRecord() {

        for (int i = 0; i < selectFiles.size(); i++) {
            MyFile myFile = selectFiles.get(i);
            myFile.setOrderNum(i + 1);
            if (myFile.getType() == MyFile.FILE_TYPE_PICTURE) {
                selectPictureFiles.add(myFile);
            } else {
                selectVideoFiles.add(myFile);
            }
        }
    }

    private void removeHistorySelect(List<MyFile> myFiles) {
        if (historySelectFiles.size() != 0) {
            for (int x = 0; x < historySelectFiles.size(); x++) {
                MyFile historySelectItem = historySelectFiles.get(x);
                for (int y = 0; y < myFiles.size(); y++) {
                    MyFile newFile = myFiles.get(y);
                    if (historySelectItem.getUrl().equals(newFile.getUrl())) {//匹配上的，说明是历史选择文件，不能添加进数据集中，否则显示的列表中会出现重复的文件，所以需要清除掉
                        myFiles.remove(newFile);
                        break;
                    }

                }
            }
        }


    }


    @Override
    public void onItemClick(CheckView checkView, int position) {

        MyFile targetFile = myFileList.get(position);
        if (targetFile.getType() == Constant.MY_FILE_TYPE_VIDEO) {//选中的是视频
            if (selectVideoFiles.contains(targetFile)) {
                removeItem(checkView, targetFile);
                selectVideoFiles.remove(targetFile);
//                if (selectVideoFiles.size() < videoLimit) {
//                }
                fileRecordAdapter.setEnableSelectVideo(true);
                //如果设置了只能选一样，当视频全部取消选择的时候，设置图片为可选状态
                if (selectOnlyOneType && selectVideoFiles.size() == 0) {
                    fileRecordAdapter.setEnableSelectPicture(true);
                    setPictureCount(0, pictureLimit);
                }
            } else {
                andItem(checkView, targetFile);
                selectVideoFiles.add(targetFile);
                //检测视频是否超限
                checkEnableSelectVideo();
                //如果只能选择一样，选择了视频，设置不能再选择图片
                if (selectOnlyOneType) {
                    fileRecordAdapter.setEnableSelectPicture(false);
                    setPictureCount(0, 0);
                }
            }
            setVideoCount(selectVideoFiles.size(), videoLimit);

        } else {//选中的是图片
            if (selectPictureFiles.contains(targetFile)) {
                removeItem(checkView, targetFile);
                selectPictureFiles.remove(targetFile);
//                if (selectPictureFiles.size() < pictureLimit) {
//                }
                fileRecordAdapter.setEnableSelectPicture(true);
                //如果设置了只能选一样，当图片全部取消选择的时候，设置视频为可选状态
                if (selectOnlyOneType && selectPictureFiles.size() == 0) {
                    fileRecordAdapter.setEnableSelectVideo(true);
                    setVideoCount(0, videoLimit);
                }
            } else {
                andItem(checkView, targetFile);
                selectPictureFiles.add(targetFile);
                //超过图片限制通知不能再选图片
                checkEnableSelectPicture();
                //如果只能选择一样，选择了图片，设置不能再选择视频
                if (selectOnlyOneType) {
                    fileRecordAdapter.setEnableSelectVideo(false);
                    setVideoCount(0, 0);
                }
            }
            setPictureCount(selectPictureFiles.size(), pictureLimit);

        }
        shouldShowMenuDone();
    }


    private void shouldShowMenuDone() {
        if (selectPictureFiles.size() == 0 && selectVideoFiles.size() == 0) {
            if (View.VISIBLE == tv_confirm.getVisibility()) {
                ScaleAnimation scaleHide = new ScaleAnimation(1f, 0f, 1f, 0f);
                scaleHide.setDuration(200);
                tv_confirm.startAnimation(scaleHide);
            }
            tv_confirm.setVisibility(View.INVISIBLE);
            //tvPreview.setVisibility(View.INVISIBLE);
        } else {
            if (View.INVISIBLE == tv_confirm.getVisibility()) {
                ScaleAnimation scaleShow = new ScaleAnimation(0f, 1f, 0f, 1f);
                scaleShow.setDuration(200);
                tv_confirm.startAnimation(scaleShow);
            }
            tv_confirm.setVisibility(View.VISIBLE);
            // tvPreview.setVisibility(View.VISIBLE);
        }
//        tv_confirm.setText(getString(R.string.selector_action_done_easy_photos, Result.count(),
//                Setting.count));
    }

    private void checkEnableSelectVideo() {
        if (selectVideoFiles.size() >= videoLimit) {
            fileRecordAdapter.setEnableSelectVideo(false);
        }
    }

    private void checkEnableSelectPicture() {
        if (selectPictureFiles.size() >= pictureLimit) {
            fileRecordAdapter.setEnableSelectPicture(false);
        }
    }

    private void andItem(CheckView checkView, MyFile targetFile) {
        selectFiles.add(targetFile);//必须先加，再设置Num
        targetFile.setOrderNum(selectFiles.size());
        checkView.setCount(selectFiles.size());
        //setButtonEnable();
    }

    private void removeItem(CheckView checkView, MyFile targetFile) {
        // checkView.removeCount();
        targetFile.setOrderNum(null);
        // selectFiles.remove(targetFile);
        int threshold = -1;
        for (int i = 0; i < selectFiles.size(); i++) {
            MyFile myFile = selectFiles.get(i);
            if (targetFile == myFile) {
                selectFiles.remove(myFile);
                threshold = i;
                i--;
                continue;
            }
            //把位于去掉选中item之后点击的item的序号，全部减1,并刷新对应的Item
            if (threshold != -1) {
                myFile.setOrderNum(myFile.getOrderNum() - 1);
                // int index = myFileList.indexOf(myFile);
                // fileRecordAdapter.notifyItemChanged(index);//局部刷新，会出现单个item 闪动，所以采用全局刷新
            }
        }

        // setButtonEnable();
    }

    private void setVideoCount(int videoCount, int videoLimit) {
        if (videoLimit == 0) {
            tv_videoCount.setVisibility(View.GONE);
        } else {
            if (!tv_videoCount.isShown()) {
                tv_videoCount.setVisibility(View.VISIBLE);
            }
            tv_videoCount.setText("视频：" + videoCount + "/" + videoLimit);
        }
    }

    private void setPictureCount(int pictureCount, int pictureLimit) {
        if (pictureLimit == 0) {
            tv_pictureCount.setVisibility(View.GONE);
        } else {
            if (!tv_pictureCount.isShown()) {
                tv_pictureCount.setVisibility(View.VISIBLE);
            }
            tv_pictureCount.setText("图片：" + pictureCount + "/" + pictureLimit);
        }
    }

    public void setListener(InteractionListener listener) {
        this.listener = listener;
    }

    public interface InteractionListener {
        void onConfirm(ArrayList<MyFile> videoFiles, ArrayList<MyFile> pictureFiles);
    }
}
